import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import LoginPage from '../views/LoginPage.vue'

const expiredTime = 5 * 60 * 1000

const loginPathReg = /^\/login[|\/loginemail|\/loginphone]/

const login_children = [
      {
        path: '/login/loginphone',
        name: 'loginphone',
        component: () => import('../views/LoginPhone.vue')
      },
      {
        path: '/login/loginemail',
        name: 'loginemail',
        component: () => import('../views/LoginEmail.vue')
      }
]

const routes: Array<RouteRecordRaw> = [
  {
    path: "/", 
    redirect: "/loginsuccess"
  },
  {
    path: '/login',
    name: 'login',
    redirect: '/login/loginemail',
    component: LoginPage,
    children: login_children
  },
  {
    path: '/loginsuccess',
    name: 'loginsuccess',
    component: () => import('../views/LoginSuccess.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  if (loginPathReg.test(to.path)){
    next();return
  }
  var token = localStorage.getItem("auth_token")
  if (!token){
    next({path: "/login"});return
  }
  var token_map = JSON.parse(token)
  var now = new Date()
  var timeDiff = now.getTime() - token_map.timestamp
  if (!(timeDiff > expiredTime)){
    next();return
  }
  next({path: "/login"});return
})

export default router
